package com.tkmybatis.hfy.sign;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;

import com.tkmybatis.hfy.utils.MD5;
import com.tkmybatis.hfy.utils.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerMapping;


import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
public class SignUtil {
	
	public static String appsecret = "71f1713b4a9e4fafbd32bc9532aa1bdd";
	public static String appkey = "adc383bdcaea40248da7f010ca3205f9";

	/**
	 * 获取签名
	 * 	1 筛选 
		获取所有请求参数，不包括字节类型参数，如文件、字节流，剔除sign字段；
		2 排序 
		将筛选的参数按照第一个字符的键值ASCII码递增排序（字母升序排序），如果遇到相同字符则按照第二个字符的键值 ASCII码递增排序，以此类推。如：foo=1, bar=2, foo_bar=3, foobar=4,排序后的顺序是bar=2, foo=1, foo_bar=3, foobar=4。
		3 拼接 
		将排序后的参数与其对应值，组合成“参数=参数值”的格式，并且把这些参数用&字符连接起来并在最后加上&appSecret=71f1713b4a9e4fafbd32bc9532aa1bdd，此时生成的字符串为待签名字符串.将待签名字符串MD5加密得出签名（sign）的值
	 * @param request
	 * @param appSecret
	 * @return
	 */
	public static String sign(HttpServletRequest request, String appSecret){
		NativeWebRequest webRequest = new ServletWebRequest(request);
		String url = request.getRequestURI();
        Map<String, String> map = (Map<String, String>) webRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
		Enumeration<String> enums = request.getParameterNames();
		Set<String> sets = new HashSet<String>();
		while(enums.hasMoreElements()){
			String key = (String)enums.nextElement();
			if(!key.equals("sign")){
				sets.add(key);
			}
		}
		// access_token也加进来排序
		String access_token = request.getHeader("access_token");
		if(StringUtils.isNotBlank(access_token)) {
			sets.add("access_token");
		}
		
		String sign = "";
		List<String> parm = new ArrayList<>();
		for(String s : sets){
			parm.add(s);
		}
		Collections.sort(parm);
		for(String s : parm){
			if("access_token".equals(s) && StringUtils.isNotBlank(access_token)) {
				sign += s + "="+ access_token + "&";
			}else {
				sign += s + "="+ request.getParameter(s) + "&";	
			}
		}
		sign += "appsecret="+appSecret;
		//参数在url上的特殊处理
		if(map != null) {
			Set<String> mapsets = map.keySet();
			for(String s : mapsets) {
				sign += "&"+map.get(s);
			}
		}
		MD5 md5 = new MD5();
		log.info("sign====="+sign);
		return md5.getMD5ofStr(sign);
	}
	
	
	public static String sign(String appkey, String timestmp, String appSecret, String path){
		String sign = "appkey="+appkey+"&timestmp="+timestmp+"&appsecret="+appSecret+"&"+path;
		MD5 md5 = new MD5();
		return md5.getMD5ofStr(sign);
	}
	
	/**
	 * 
	 * @param params	form表单上的参数
	 * @param appSecret	
	 * @param map		url上的参数，key随便取名字
	 * @return
	 */
	public static String sign(Map<String, String> params, String appSecret, Map<String, String> map){
		Set<String> sets = params.keySet();
		String sign = "";
		int size = sets.size();
		String parm[] = new String[size];
		int index = 0;
		for(String s : sets){
			parm[index] = s;
			index++;
		}
		Arrays.sort(parm);
		for(String s : parm){
			sign += s + "="+ params.get(s) + "&";
		}
		sign += "appsecret="+appSecret;
		if(map != null && map.size() > 0) {
			Set<String> keys = map.keySet();
			sign += "&"+map.get(keys.iterator().next());
		}
		MD5 md5 = new MD5();
		return md5.getMD5ofStr(sign);
	}
	
	
//	public static boolean checkSign(HttpServletRequest request) throws Exception {
//		String appkey = request.getParameter("appkey");
//		String sign = request.getParameter("sign");
//		if(StringUtils.isBlank(appkey) || StringUtils.isBlank(sign)) {
//			return false;
//		}
//		SystemService systemService = SpringUtil.getBean(SystemService.class);
//		String appsecret = systemService.getAppsecret(appkey);
//		log.info("appsecret======"+appsecret);
//		if(appsecret != null) {
//			String sourceSign = SignUtil.sign(request, appsecret);
//			log.info("sourceSign===="+sourceSign);
//			log.info("sign===="+sign);
//			if(sourceSign.equals(sign)) {
//				return true;
//			}
//		}
//		return false;
//	}
	
	/*public static void main(String[] args) throws Exception {
		// url上面的参数
		Map<String, String> path = new HashMap<String, String>();
		path.put("id", "534124885652275200");
		// form表单中的参数
		Map<String, String> param = new HashMap<String, String>();
		param.put("appkey", appkey);
		param.put("timestamp", (System.currentTimeMillis()/1000)+"");
		String params = "";
		// 参数签名
		String sign = sign(param, appsecret, path);
		for(String s : param.keySet()){
			params += s+"="+param.get(s) + "&";
		}
		params += "sign="+sign;
		String url = "http://192.168.141.208:8106/es/upload/file/getFile/534124885652275200?"+params;
		log.info(HttpUtil.httpRequest(url, HttpUtil.GET, null, null).toString());
	}*/
}
